# -*- coding: utf-8 -*-
import optparse

import pyglet
from pyglet.gl import *
from pyglet.window import key

import sys

import camera
import isometric

VERSION = "1.1"

class EditableMap(isometric.Map):
    def __init__(self, filename):
        try:
            self.parse_map(filename)
        except IOError:
            self.load_empty_file()
            
        self.draw_batch = pyglet.graphics.Batch()
        self.reindex()

        self.filename = filename

        self.cursorx = 0
        self.cursory = 0

        img = pyglet.resource.image("arrow.png")
        self.cursor = pyglet.sprite.Sprite(img, 0, 0)

        self.selected_tile_type = 1

        self.cursor_label = pyglet.text.Label("(%i, %i)" % (self.cursorx, self.cursory))
        self.fps_display = pyglet.clock.ClockDisplay()
        self.selected_tile_box = pyglet.graphics.vertex_list(4,
                                                             ("v2f", (0, 0,
                                                                      0, isometric.tile_height,
                                                                      isometric.tile_width, isometric.tile_height,
                                                                      isometric.tile_width, 0)),
                                                              ("c3B", (0, 100, 255,
                                                                       0, 100, 255,
                                                                       0, 100, 255, 
                                                                       0, 100, 255))
                                                             )
    def draw(self, cam, width, height):
        isometric.Map.draw(self, cam, width, height)

        cam.focus(width, height)
        x, y = isometric.isometric_map_coord_to_world_coord(self.cursorx,
                                                            self.cursory)
        glTranslatef(x + 50 - self.cursor.width/2, y+25, 0)
        self.cursor.draw()

        cam.hud_mode(width, height)
        glTranslatef(width - self.cursor_label.content_width - 20, 20, 0)
        self.cursor_label.draw()

        cam.hud_mode(width, height)
        glTranslatef(width - isometric.tile_width - 20, 20 + self.cursor_label.content_height, 0)
        self.selected_tile_box.draw(GL_QUADS)
        isometric.tile_images[self.selected_tile_type].blit(0,0)

        cam.hud_mode(width, height)
        glTranslatef(20, 20, 0)
        self.fps_display.draw()

    def move_cursor(self, dx, dy):
        self.cursorx += dx
        self.cursory += dy
        self.cursor_label = pyglet.text.Label("(%i, %i)" % (self.cursorx, self.cursory))

    def load_empty_file(self):
        self.tile_layer = isometric.Array2D()
        self.name = "New map"

    def dump(self, filename=None):
        if filename is None:
            filename = self.filename
        f = open(filename, "w")
        header = """MAP
VER %s
NAME %s
WIDTH %i
HEIGHT %i
FOCUS TILE %i %i

"""
        f.write(header % (VERSION, self.name, self.tile_layer.width(), self.tile_layer.height(), 0, 0))
        f.write("BEGIN TILES\n\n")
        
        for y in xrange(self.tile_layer.ymin, self.tile_layer.ymax + 1):
            for x in xrange(self.tile_layer.xmin, self.tile_layer.xmax + 1):
                tile = self.tile_layer.get(x, y)
                f.write("TILE\nTYPE %i\nATTRIBUTES %i\n\n" % (tile.type, tile.attr))
        f.write("END TILES\n\n")
        f.write("BEGIN ENEMIES\n\n")
        # Fan, man måste spara dem separat varje gång
        f.write("END ENEMIES\n\n")
        f.write("BEGIN BUILDINGS\n\n")
        f.write("END BUILDINGS")

        f.close()
        print "File saved"

    def change_tile_at_cursor(self):
        #tile_index = self.width*self.cursory + self.cursorx
        # 
        #print self.width, self.height
        #if self.cursory > self.height - 1:
        #    print "Not fitting in height"
        #    return
        #if self.cursorx > self.width - 1:
        #    print "Not fitting in width"
        #    return
        
        #y, x = divmod(tile_index, self.width)
        #print x, y
        #print self.cursorx, self.cursory, "-"
        #assert(y == self.cursory)
        #assert(self.cursorx == x)
        
        #print tile_index - self.width*self.height + 1
        #for index in xrange(tile_index - self.width*self.height + 2):
        #    y, x = divmod(len(self.tile_layer) + index, self.width)
        #    self.tile_layer.append(isometric.IsometricTile(x, y, 0, 0))
        #    if x > self.width: self.width = x
        #    if y > self.height: self.height = y
        #    print "Added tile"
        self.tile_layer.set(self.cursorx, self.cursory, isometric.IsometricTile(self.selected_tile_type, 0))
        self.tile_layer.fill_empty(isometric.IsometricTile(self.selected_tile_type, 0))
        self.reindex()

def main():
    win_width = 1024
    win_height = 786
    
    window = pyglet.window.Window(win_width, win_height)

    if len(sys.argv) < 2: 
        filename = "new_map.map"
    else: filename = sys.argv[1]

    map = EditableMap(filename)

    glClearColor(0, 1, 0, 0)
    glEnable(GL_BLEND)
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

    cam = camera.Camera((0,0),scale=20)

    pyglet.clock.set_fps_limit(60)
    
    def dontstopthemusic(dt):
        pass

    @window.event
    def on_draw():
        window.clear()
        cam.focus(window.width, window.height)
        map.draw(cam, window.width, window.height)

    @window.event
    def on_key_press(sym, mod):
        if sym == key.UP:
            cam.y += cam.scale
        if sym == key.DOWN:
            cam.y -= cam.scale
        if sym == key.LEFT:
            cam.x -= cam.scale
        if sym == key.RIGHT:
            cam.x += cam.scale
        if sym == key.MINUS:
            cam.scale *= 2
        if sym == key.PLUS:
            cam.scale /= 2.0
        if sym == key.A:
            map.move_cursor(-1, 0)
        if sym == key.D:
            map.move_cursor(1, 0)
        if sym == key.W:
            map.move_cursor(0, 1)
        if sym == key.S:
            map.move_cursor(0, -1)
        if sym == key.F2:
            map.dump()
        if sym == key.TAB:
            map.selected_tile_type = (map.selected_tile_type + 1) % len(isometric.tile_images)
        if sym == key.SPACE:
            map.change_tile_at_cursor()

    print """Up down left right: Control camera
+ -: zoom in and out
w a s d: Move cursor
F2: save file
TAB: change tile type
SPACE: apply tile"""
    pyglet.clock.schedule_interval(dontstopthemusic, 1/60.0)

    pyglet.app.run()
    

if __name__ == "__main__":
    main()
    
